//定义关于counter的store
import {
	defineStore
} from 'pinia'
import {
	USER_INFO,
	TOKEN,
	CONFIG
} from '@/config/cachekey';
import Cache from '@/utils/cache'

import {
	getUserInfo,
	getUserInfoBoolean
} from '@/api/app.js';

/*defineStore 是需要传参数的，其中第一个参数是id，就是一个唯一的值，
简单点说就可以理解成是一个命名空间.
第二个参数就是一个对象，里面有三个模块需要处理，第一个是 state，
第二个是 getters，第三个是 actions。
*/
export const useUserStore = defineStore("user", {
	state: () => ({
		userInfo: {

		},
		token: undefined,
		isLogin: false,
		isHideTabbar: false,
		isNotChange: true, // 是否需要改变tabbar的显示状态
		isApplyfor: false, // 是否申请过成为企业
		addressInfo: {
			longitude: "",
			latitude: "",
			city: "",
			district: "",
			nation: "",
			province: "",
			street: ""
		}
	}),
	getters: {
		getUser() {
			return this.userInfo
		}
	},
	actions: {
		getUserFun(isChange = false) {
			return new Promise((resolve, reject) => {
				if (Cache.get(TOKEN)) {
					getUserInfo().then(res => {
						if (res.code == 200) {
							this.isLogin = true;
							this.userInfo = res.data;
							if(isChange) {
								if (res.data.userType == 1) {
									uni.hideTabBar({
										animation: false
									})
									this.isHideTabbar = true;
								} else if (res.data.userType == 2) { // 游客
									this.isHideTabbar = false;
									this.getUserInfoBooleanFun();
									uni.showTabBar();
								} else {
									this.isHideTabbar = false;
									uni.showTabBar();
								}
							}
						} else {
							this.isLogin = false;
							this.isHideTabbar = false;
							if(isChange) {
								uni.showTabBar();
							}
						}
						resolve(res)
					}).catch(err => {
						reject(error)
					})
				} else {
					this.isHideTabbar = false;
					uni.showTabBar();
				}
			})
		},
		getUserInfoBooleanFun() {
			getUserInfoBoolean().then(res => {
				console.log(res);
				if (res.code == 200) {
					if (res.data) {
						this.isApplyfor = true;
					}
				}
			})
		},
		setUser(data) {
			this.userInfo = data;
			if (data.userType == 1) {
				console.log("==========隐藏底部");
				this.isNotChange = true;
				console.log(this.isNotChange);
				this.isHideTabbar = true;
			} else {
				this.isHideTabbar = false;
				uni.showTabBar();
			}
			this.token = data.token;
			Cache.set(TOKEN, data.token, 59 * 24 * 60 * 60);
		},
		setAddress(data) {
			this.addressInfo = data;
		},
		logOut() {
			this.token = undefined;
			this.isLogin = false;
			this.isHideTabbar = false;
			uni.showTabBar();
			this.userInfo = {};
			Cache.remove(TOKEN);
			Cache.remove(USER_INFO);
		}
	}
})